package zipcode.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import to.ZipcodeTO;

public class ZipcodeService {
	private ZipcodeDAO dao;
	@SuppressWarnings("unused")
	private HashMap<String, HashMap<?,?>> address;
	private HashMap<String,ArrayList<Integer>> sido, gugun, dong; 
	private String[] addressUnit = {"읍","면","동","구","군","시","도"};
	
	public ZipcodeService(ZipcodeDAO dao) throws SQLException{
			this.dao = dao;
			ArrayList<ZipcodeTO> allAddress = dao.selectMemberByCondition(new HashMap<String,Object>());
			sido = new HashMap<String,ArrayList<Integer>>();
			gugun = new HashMap<String,ArrayList<Integer>>();
			dong = new HashMap<String,ArrayList<Integer>>();
			ZipcodeTO zipcodeTO = null;
			for (int i = 0; i < allAddress.size(); i++){
				zipcodeTO = allAddress.get(i);
				if(!sido.containsKey(zipcodeTO.getSido())){
					sido.put(zipcodeTO.getSido(), new ArrayList<Integer>());
				}
				sido.get(zipcodeTO.getSido()).add(i);
				
				if(!gugun.containsKey(zipcodeTO.getGugun())){
					gugun.put(zipcodeTO.getGugun(), new ArrayList<Integer>());
				}
				gugun.get(zipcodeTO.getGugun()).add(i);
				
				if(!dong.containsKey(zipcodeTO.getDong())){
					dong.put(zipcodeTO.getDong(), new ArrayList<Integer>());
				}
				dong.get(zipcodeTO.getDong()).add(i);
			}
			address = new HashMap<String,HashMap<?,?>>();
	}
	
	public ArrayList<ZipcodeTO> selectZipcode(HashMap<String,Object> condition) throws SQLException{
		Integer addressUnitLevel = Integer.parseInt(condition.get("addressUnitLevel").toString());
		ArrayList<ZipcodeTO> result = null;
		
		if(addressUnitLevel > 4){
			result = dao.selectMemberByCondition(condition);
			if(result.size() == 0){
				condition.put("gugun", condition.get("sido").toString() + addressUnit[addressUnitLevel]);
				condition.remove("sido");
				System.out.println(condition.get("gugun"));
				result = dao.selectMemberByCondition(condition);
			}
		}else if(addressUnitLevel > 2){
			condition.put("gugun", condition.get("gugun").toString() + addressUnit[addressUnitLevel]);
			result = dao.selectMemberByCondition(condition);
		}else{
			condition.put("dong", condition.get("dong").toString() + addressUnit[addressUnitLevel]);
			result = dao.selectMemberByCondition(condition);
		}
		return result;
	}
}